package com.yalpuz.controller;

import com.yalpuz.entity.User;
import com.yalpuz.service.UserService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Controller
public class DefaultController {
    @Resource
    private CacheManager cacheManager;

    @Resource
    private UserService userService;

    @PostConstruct
    public void init() {
        System.out.println("初始化");
    }

    @RequestMapping("/index")
    @Transactional
    public String index(ModelMap modelMap) {

        User user = new User();
        user.setPassword(UUID.randomUUID().toString());
        userService.save(user);
        Page<User> page = userService.list();
        System.out.println("page:" + page.getTotalElements());

        Page<User> page2 = userService.list2();
        System.out.println("page2:" + page2.getTotalElements());

        Cache menuCache = cacheManager.getCache("menuCache");
        Cache.ValueWrapper wrapper = menuCache.get("now");
        Date date;
        if (wrapper == null) {
            date = new Date();
            menuCache.put("now", date);
        } else {
            date = (Date) wrapper.get();
        }
        modelMap.put("now", date);
        return "/index";
    }
}
